<template lang="pug">
div
  Row
    Col(:span=16)
      Form(ref='form', :label-width=80, :model='formData', :rules='validateRules')
        FormItem(label='标题', prop='title', required)
          Input(type='text', v-model='formData.title')
        FormItem(label='分类', prop='category', required)
          SelectCategory(module='media', @change='setCategory')
        FormItem(label='封面')
          CoverUploader(@on-upload='onUploadCover')
        FormItem(label='简介')
          Editor(type='textarea', :rows=5, v-model='formData.body')
        FormItem
          Button(type='primary', :loading='loading', @click='submit') 提交
          | &nbsp;&nbsp;
          Button(type='ghost', @click='$router.go(-1)') 取消
</template>

<script>
import Editor from '@/components/Editor'
import CoverUploader from '@/components/CoverUploader'
import SelectCategory from '@/components/SelectCategory'
import mediaApi from '@/apis/media'

export default {
  components: {
    Editor,
    CoverUploader,
    SelectCategory
  },
  data () {
    return {
      loading: false,
      formData: {
        group_id: this.$store.state.app.id,
        title: '',
        body: '',
        cover: '',
        category: null
      },
      validateRules: {
        title: { required: true, message: '请填写标题' },
        category: {
          type: 'object',
          required: true,
          message: '请选择分类',
          fields: {
            id: { type: 'string', required: true },
            name: { type: 'string' }
          }
        }
      }
    }
  },
  methods: {
    onUploadCover (file) {
      this.formData.cover = file.id
    },
    setCategory (e) {
      this.formData.category = {
        id: e.value,
        name: e.label
      }
    },
    submit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          mediaApi.postMedia(this.formData)
            .then(media => {
              // console.log(media)
              this.loading = false
              this.$router.push('/media')
            })
        }
      })
    }
  }
}
</script>
